package com.qianclass.talklive.app.view;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.TextView;

import com.qianclass.talklive.R;
import com.qianclass.talklive.app.utils.DensityUtil;

public class LoadMoreListView extends ListView implements OnScrollListener {

	
	private boolean isLoadingMore = false;
	private TextView footerView;
	private int mFooterMeasuredHeight;
	
	//下拉刷新状态
	private final int PULL_LOADMORE = 0;

	private int mDownY;

	private OnLoadMoreListener mListener;
	private RotateAnimation mUpAnimation;
	private RotateAnimation mDownAnimation;
	private int mExtra;
	private Context mContext;

	private Handler mHandler = new Handler();

	//定义一个监听刷新的接口
	public interface OnLoadMoreListener{
		
		//创建可被回调的函数
		//加载更多
		void onLoadingMore();
	}
	
	public void setOnLoadMoreListener(OnLoadMoreListener listener){
		mListener = listener;
	}
	
	public LoadMoreListView(Context context) {
		super(context);
		mContext = context;
		init();
	}

	public LoadMoreListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}

	private void init() {
		
		//初始化footer的视图
		initFooterView();

		setOnScrollListener(this);
	}

	/**
	 * 初始化footer的视图
	 */
	private void initFooterView() {
		//填充view
		footerView = new TextView(mContext);
		footerView.setTextSize(DensityUtil.sp2px(mContext, 10));
		footerView.setGravity(Gravity.CENTER);
		footerView.setText(mContext.getString(R.string.course_load_more));

		footerView.measure(0, 0);
		mFooterMeasuredHeight = footerView.getMeasuredHeight();
		footerView.setPadding(0, -mFooterMeasuredHeight, 0, 0);

		addFooterView(footerView);
	}

	public void setLoadingStatus(boolean status){
		if (status) {
			footerView.setText(mContext.getString(R.string.course_load_more));
		} else {
			footerView.setText(mContext.getString(R.string.course_no_more_data));
		}

		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				footerView.setPadding(0, 0, 0,-mFooterMeasuredHeight);
			}
		}, 200);

		isLoadingMore = false;

		invalidate();
	}

	//当滑动的状态改变时会被调用
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(scrollState == OnScrollListener.SCROLL_STATE_IDLE &&
				getLastVisiblePosition() == (getCount() - 1) &&
				! isLoadingMore){
			//表示现在是处于空闲的状态
			isLoadingMore = true;
			
			footerView.setPadding(0, 0, 0, 0);
			setSelection(getCount());
		
			if(mListener != null){
				mListener.onLoadingMore();
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		
	}
}
